#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "../libs/ikcp.h"

#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 8888
#define BUFFER_SIZE 1024

int main() {
	// 创建UDP套接字
	int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if (sockfd == -1) {
		std::cerr << "Create socket failed" << std::endl;
		return -1;
	}

	// 设置服务器地址结构体
	struct sockaddr_in serverAddr;
	serverAddr.sin_family      = AF_INET;
	serverAddr.sin_port        = htons(SERVER_PORT);
	serverAddr.sin_addr.s_addr = inet_addr(SERVER_IP);

	// 创建KCP对象
	ikcpcb *kcp = ikcp_create(0x11223344, (void *) sockfd);
	kcp->output = [](const char *buf, int len, ikcpcb *kcp, void *user) {
		int                sockfd = (int) user;
		struct sockaddr_in serverAddr;
		serverAddr.sin_family      = AF_INET;
		serverAddr.sin_port        = htons(SERVER_PORT);
		serverAddr.sin_addr.s_addr = inet_addr(SERVER_IP);
		sendto(sockfd, buf, len, 0, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
	};

	// 发送消息
	const char *message = "Hello, server!";
	ikcp_send(kcp, message, strlen(message));

	char buffer[BUFFER_SIZE];
	while (true) {
		// 更新KCP状态
		ikcp_update(kcp, iclock());

		// 处理KCP消息
		while (true) {
			int peekLen = ikcp_peeksize(kcp);
			if (peekLen < 0) {
				break;
			}
			int recvDataLen = ikcp_recv(kcp, buffer, peekLen);
			if (recvDataLen > 0) {
				std::cout << "Received message from server: " << buffer << std::endl;
			}
		}
	}

	// 释放KCP对象和关闭套接字
	ikcp_release(kcp);
	close(sockfd);

	return 0;
}
